﻿//--------------------------------------------------------------------
// All Rights Reserved , Copyright (C) 2012 ,  TECH, Ltd. 
//--------------------------------------------------------------------

using System;
using System.Data;
using System.Collections.Generic;
using System.Reflection;
using System.ServiceModel;

namespace RDIFramework.ServiceAdapter
{
    using RDIFramework.BusinessEntity;
    using RDIFramework.IService;
	using RDIFramework.Utilities;
	

	/// <summary>
	/// RoleService
	/// 服务层
	/// 
	/// 修改记录
	/// 
    ///     2012-06-08 EricHu 重新组织RoleService
	///		2012-03-02 版本：1.0 EricHu 建立。
	///		
	/// 版本：1.0
	///
	/// <author>
	///		<name>EricHu</name>
	///		<date>2012-03-02</date>
	/// </author> 
	/// </summary>
	[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
	public class RoleService : System.MarshalByRefObject, IRoleService
	{
		private readonly string serviceName = RDIFrameworkMessage.RoleService;
		
		/// <summary>
		/// .NET快速开发整合框架（RDIFramework.NET）数据库连接
		/// </summary>
        private readonly string RDIFrameworkDbConection = SystemInfo.RDIFrameworkDbConection;

        #region public int Add(UserInfo userInfo, PiRoleEntity entity, out string statusCode, out string statusMessage):新增实体
        /// <summary>
		/// 新增实体
		/// </summary>
		/// <param name="userInfo">用户</param>
		/// <param name="entity">实体</param>
		/// <param name="statusCode">返回状态码</param>
		/// <param name="statusMessage">返回状态信息</param>
		/// <returns>受影响的行数</returns>
		public int Add(UserInfo userInfo, PiRoleEntity entity, out string statusCode, out string statusMessage)
		{
            int returnValue = 0;
            statusCode = string.Empty;

            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    PiRoleManager manager = new PiRoleManager(dbProvider, userInfo);
                    returnValue = manager.AddEntity(entity,out statusCode);
                    statusMessage = manager.GetStateMessage(statusCode);
                    LogManager.Instance.Add(dbProvider, userInfo, this.serviceName, RDIFrameworkMessage.RoleService_Add, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }
			
			return returnValue;
		}
        #endregion

        #region public DataTable GetDT(UserInfo userInfo):取得列表
        /// <summary>
		/// 取得列表
		/// </summary>
		/// <param name="userInfo">用户</param>
		/// <returns>数据表</returns>
		public DataTable GetDT(UserInfo userInfo)
		{

			DataTable dataTable = new DataTable(PiRoleTable.TableName);

            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    // 取得列表
                    PiRoleManager manager = new PiRoleManager(dbProvider, userInfo);
                    dataTable = manager.GetDT(PiRoleTable.FieldDeleteMark, 0, PiRoleTable.FieldSortCode);
                    dataTable.TableName = PiRoleTable.TableName;
                    LogManager.Instance.Add(dbProvider, userInfo, this.serviceName, RDIFrameworkMessage.RoleService_GetDT, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }

            }
			return dataTable;
		}
        #endregion

        #region public DataTable GetDTByPage(UserInfo userInfo,out int recordCount,int pageIndex=1,int pageSize=20,string whereConditional = "",string order = "") 获取角色分页列表
        /// <summary>
        /// 获取角色分页列表
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="recordCount">所有角色数</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">分页大小（默认20条）</param>
        /// <param name="whereConditional">条件表达式</param>
        /// <param name="order">排序字段</param>
        /// <returns>数据表</returns>
        public DataTable GetDTByPage(UserInfo userInfo, out int recordCount, int pageIndex = 1, int pageSize = 20, string whereConditional = "", string order = "")
        {
            // 写入调试信息
            #if (DEBUG)
				int milliStart = BusinessLogic.StartDebug(userInfo, MethodBase.GetCurrentMethod());
            #endif

            // 加强安全验证防止未授权匿名调用
            #if (!DEBUG)
                LogOnService.UserIsLogOn(userInfo);
            #endif

            DataTable dataTable = new DataTable(PiRoleTable.TableName);

            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    LogManager.Instance.Add(dbProvider, userInfo, this.serviceName, RDIFrameworkMessage.RoleService_GetDT, MethodBase.GetCurrentMethod());
                    // 取得列表
                    PiRoleManager manager = new PiRoleManager(dbProvider, userInfo);
                    if (string.IsNullOrEmpty(whereConditional))
                    {
                        whereConditional = PiRoleTable.FieldDeleteMark + " = 0 ";
                    }
                    else
                    {
                        whereConditional += " AND " + PiRoleTable.FieldDeleteMark + " = 0 ";
                    }

                    dataTable = manager.GetDTByPage(out recordCount, pageIndex, pageSize, whereConditional, order);
                    dataTable.TableName = PiRoleTable.TableName;
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }

            // 写入调试信息
            #if (DEBUG)
				BusinessLogic.EndDebug(MethodBase.GetCurrentMethod(), milliStart);
            #endif

            return dataTable;
        }
        #endregion

        #region public PiRoleEntity GetEntity(UserInfo userInfo, string id):取得实体
        /// <summary>
		/// 取得实体
		/// </summary>
		/// <param name="userInfo">用户</param>
		/// <param name="id">主键</param>
		/// <returns>实体</returns>
		public PiRoleEntity GetEntity(UserInfo userInfo, string id)
		{

			PiRoleEntity entity = null;
            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    PiRoleManager manager = new PiRoleManager(dbProvider, userInfo);
                    entity = manager.GetEntity(id);
                    LogManager.Instance.Add(dbProvider, userInfo, this.serviceName, RDIFrameworkMessage.RoleService_GetEntity, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }

			return entity;
		}
        #endregion

        #region public int Update(UserInfo userInfo, PiRoleEntity entity, out string statusCode, out string statusMessage):更新实体
        /// <summary>
		/// 更新实体
		/// </summary>
		/// <param name="userInfo">用户</param>
		/// <param name="entity">实体</param>
		/// <param name="statusCode">返回状态码</param>
		/// <param name="statusMessage">返回状态信息</param>
		/// <returns>影响的行数</returns>
		public int Update(UserInfo userInfo, PiRoleEntity entity, out string statusCode, out string statusMessage)
		{
			int returnValue = 0;
			statusCode = string.Empty;

            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    PiRoleManager manager = new PiRoleManager(dbProvider, userInfo);
                    returnValue = manager.UpdateEntity(entity,out statusCode);
                    statusMessage = manager.GetStateMessage(statusCode);
                    LogManager.Instance.Add(dbProvider, userInfo, this.serviceName, RDIFrameworkMessage.RoleService_Update, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }

            return returnValue;
		}
        #endregion

        #region public DataTable GetDTByIds(UserInfo userInfo, string[] ids):根据主键数组得到角色信息
        /// <summary>
		/// 根据主键数组得到角色信息
		/// </summary>
		/// <param name="userInfo">用户</param>
		/// <param name="ids">主键</param>
		/// <returns>数据表</returns>
		public DataTable GetDTByIds(UserInfo userInfo, string[] ids)
		{
			DataTable dataTable = new DataTable(PiRoleTable.TableName);

            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    PiRoleManager manager = new PiRoleManager(dbProvider, userInfo);
                    dataTable = manager.GetDT(PiRoleTable.FieldId, ids, PiRoleTable.FieldSortCode);
                    dataTable.TableName = PiRoleTable.TableName;
                    LogManager.Instance.Add(dbProvider, userInfo, this.serviceName, RDIFrameworkMessage.RoleService_GetRoleUserIds, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }
			return dataTable;
		}
        #endregion

        #region public DataTable GetDTByValues(UserInfo userInfo, string[] names, object[] values):根据条件获得角色列表
        /// <summary>
		/// 根据条件获得角色列表
		/// </summary>
		/// <param name="userInfo">用户</param>
		/// <param name="names">字段</param>
		/// <param name="values">值</param>
		/// <returns>数据表</returns>
		public DataTable GetDTByValues(UserInfo userInfo, string[] names, object[] values)
		{
			DataTable dataTable = new DataTable(PiRoleTable.TableName);

            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    // 依條件獲取資料列表
                    PiRoleManager manager = new PiRoleManager(dbProvider, userInfo);
                    dataTable = manager.GetDT(names, values);
                    dataTable.TableName = PiRoleTable.TableName;
                    LogManager.Instance.Add(dbProvider, userInfo, this.serviceName, RDIFrameworkMessage.RoleService_GetDTByValues, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }

			return dataTable;
		}
        #endregion

        #region public int BatchSave(UserInfo userInfo, List<PiRoleEntity> entites):批量保存角色数据
        /// <summary>
		/// 批量保存角色数据
		/// </summary>
		/// <param name="userInfo">用户</param>
		/// <param name="entites">实体列表</param>
		/// <returns>影响的行数</returns>
		public int BatchSave(UserInfo userInfo, List<PiRoleEntity> entites)
		{
			int returnValue = 0;

            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);                   
                    dbProvider.BeginTransaction();
                    PiRoleManager manager = new PiRoleManager(dbProvider, userInfo);
                    returnValue = manager.BatchSave(entites);
                    LogManager.Instance.Add(dbProvider, userInfo, this.serviceName, RDIFrameworkMessage.RoleService_BatchSave, MethodBase.GetCurrentMethod());
                    dbProvider.CommitTransaction();
                }
                catch (Exception ex)
                {
                    dbProvider.RollbackTransaction();
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }
			return returnValue;
		}
        #endregion

        #region public int Delete(UserInfo userInfo, string id):物理刪除角色
        /// <summary>
        /// 物理刪除角色
		/// </summary>
		/// <param name="userInfo">用户</param>
		/// <param name="id">主键</param>
		/// <returns>受影响的行数</returns>
		public int Delete(UserInfo userInfo, string id)
		{
			int returnValue = 0;

            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    PiRoleManager manager = new PiRoleManager(dbProvider, userInfo);
                    returnValue = manager.Delete(id);
                    LogManager.Instance.Add(dbProvider, userInfo, this.serviceName, RDIFrameworkMessage.RoleService_Delete, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }

			return returnValue;
		}
        #endregion

        #region public int BatchDelete(UserInfo userInfo, string[] ids):批量物理删除角色
        /// <summary>
		/// 批量物理删除角色
		/// </summary>
		/// <param name="userInfo">用户</param>
		/// <param name="ids">主键数组</param>
		/// <returns>影响的行数</returns>
		public int BatchDelete(UserInfo userInfo, string[] ids)
		{
            int returnValue = 0;

            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    dbProvider.BeginTransaction();
                    PiRoleManager roleManager = new PiRoleManager(dbProvider, userInfo);
                    returnValue = roleManager.BatchDelete(ids);                   
                    dbProvider.CommitTransaction();
                    LogManager.Instance.Add(dbProvider, userInfo, this.serviceName, RDIFrameworkMessage.RoleService_BatchDelete, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                      dbProvider.RollbackTransaction();
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }
			return returnValue;
		}
        #endregion

        #region public int SetDeleted(UserInfo userInfo, string[] ids):批量逻辑删除角色
        /// <summary>
        ///  批量逻辑删除角色
		/// </summary>
		/// <param name="userInfo">用户</param>
		/// <param name="ids">主键数组</param>
		/// <returns>影响的行数</returns>
		public int SetDeleted(UserInfo userInfo, string[] ids)
		{
			int returnValue = 0;
            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    PiRoleManager manager = new PiRoleManager(dbProvider, userInfo);
                    returnValue = manager.SetDeleted(ids);
                    LogManager.Instance.Add(dbProvider, userInfo, this.serviceName, RDIFrameworkMessage.RoleService_SetDeleted, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }
			return returnValue;
		}
        #endregion

        #region public int EliminateRoleUser(UserInfo userInfo, string roleId):移除角色用户关联
        /// <summary>
        /// 移除角色用户关联
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="roleId">角色主键</param>
        /// <returns>影响行数</returns>
        public int EliminateRoleUser(UserInfo userInfo, string roleId)
        {
            int returnValue = 0;
            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    PiUserRoleManager userRoleManager = new PiUserRoleManager(dbProvider, userInfo);
                    returnValue = userRoleManager.EliminateRoleUser(roleId);
                    LogManager.Instance.Add(dbProvider, userInfo, this.serviceName, RDIFrameworkMessage.RoleService_EliminateRoleUser, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }
            return returnValue;
        }
        #endregion

        #region public string[] GetRoleUserIds(UserInfo userInfo, string roleId):获得角色中的用户主键
        /// <summary>
        /// 获得角色中的用户主键
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="roleId">角色主键</param>
        /// <returns>用户主键</returns>
        public string[] GetRoleUserIds(UserInfo userInfo, string roleId)
        {
            string[] returnValue = null;
            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    PiUserRoleManager userRoleManager = new PiUserRoleManager(dbProvider, userInfo);
                    returnValue = userRoleManager.GetUserIds(roleId);
                    LogManager.Instance.Add(dbProvider, userInfo, serviceName, RDIFrameworkMessage.RoleService_GetRoleUserIds, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }

            return returnValue;
        }
        #endregion

        #region ublic int AddUserToRole(UserInfo userInfo, string roleId, string[] addUserIds):用户添加到角色
        /// <summary>
        /// 用户添加到角色
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="roleId">角色主键</param>
        /// <param name="addUserIds">用户主键</param>
        /// <returns>影响行数</returns>
        public int AddUserToRole(UserInfo userInfo, string roleId, string[] addUserIds)
        {
            int returnValue = 0;
            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    PiUserRoleManager userRoleManager = new PiUserRoleManager(dbProvider, userInfo);
                    // 小心异常，检查一下参数的有效性
                    if (addUserIds != null)
                    {
                        returnValue += userRoleManager.AddToRole(addUserIds, roleId);
                    }
                    LogManager.Instance.Add(dbProvider, userInfo, serviceName, RDIFrameworkMessage.RoleService_AddUserToRole, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }

            return returnValue;
        }
        #endregion

        #region  public int RemoveUserFromRole(UserInfo userInfo, string roleId, string[] userIds):将用户从角色中移除
        /// <summary>
        /// 将用户从角色中移除
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="roleId">角色主键</param>
        /// <param name="userIds">用户主键</param>
        /// <returns>影响行数</returns>
        public int RemoveUserFromRole(UserInfo userInfo, string roleId, string[] userIds)
        {
            int returnValue = 0;
            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    dbProvider.BeginTransaction();
                    PiUserRoleManager userRoleManager = new PiUserRoleManager(dbProvider, userInfo);
                    if (userIds != null)
                    {
                        returnValue += userRoleManager.RemoveFormRole(userIds, roleId);
                    }
                    
                    LogManager.Instance.Add(dbProvider, userInfo, serviceName, RDIFrameworkMessage.RoleService_RemoveUserFromRole, MethodBase.GetCurrentMethod());
                    dbProvider.CommitTransaction();
                }
                catch (Exception ex)
                {
                    dbProvider.RollbackTransaction();
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }

            return returnValue;
        }
        #endregion

        #region public int ClearRoleUser(UserInfo userInfo, string roleId) 清除角色用户关联
        /// <summary>
        /// 清除角色用户关联
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="roleId">角色主键</param>
        /// <returns>影响行数</returns>
        public int ClearRoleUser(UserInfo userInfo, string roleId)
        {
            // 写入调试信息
            #if (DEBUG)
            int milliStart = BusinessLogic.StartDebug(userInfo, MethodBase.GetCurrentMethod());
            #endif

            // 加强安全验证防止未授权匿名调用
            #if (!DEBUG)
                LogOnService.UserIsLogOn(userInfo);
            #endif

            int returnValue = 0;
            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    PiUserRoleManager userRoleManager = new PiUserRoleManager(dbProvider, userInfo);
                    returnValue = userRoleManager.ClearRoleUser(roleId);
                    LogManager.Instance.Add(dbProvider, userInfo, serviceName, RDIFrameworkMessage.RoleService_ClearRoleUser, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }

            // 写入调试信息
            #if (DEBUG)
            BusinessLogic.EndDebug(MethodBase.GetCurrentMethod(), milliStart);
            #endif

            return returnValue;
        }
        #endregion
    }
}
